﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace GpCommon.Helpers
{
    public class HttpHelper
    {
        public static int MaxDefaultCount = 5;
        public static List<long> ResponseTotalSize = new List<long>();
        public static DateTime StartTime = DateTime.Now;

        private static HttpClient _httpClient = null;

        public static HttpClient Client
        {
            get
            {
                if( _httpClient == null)
                {
                    StartTime = DateTime.Now;
                    _httpClient = new HttpClient(new ResponseSizeHandler());
                    _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("PostmanRuntime/7.41.1");
                    _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0");
                    //_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
                    //_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("deflate"));
                    //_httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("br"));
                    _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
                    _httpClient.Timeout = new TimeSpan(0, 0, 20);
                }
                return _httpClient;
            }
        }
        public class ResponseSizeHandler : DelegatingHandler
        {
            public ResponseSizeHandler() : base(new HttpClientHandler()) // 初始化内部处理程序
            {
            }
            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                // 发送请求并等待响应
                var response = await base.SendAsync(request, cancellationToken);

                long? length = response.Content?.Headers?.ContentLength;
                if(length != null)
                {
                    ResponseTotalSize.Add((long)length);
                }

                return response;
            }
        }
    }


}
